<template>
  <div>
    <ZgDialog
      :width="view.width"
      :top="view.top"
      :title="view.title"
      v-model="visible"
      @ok="save">
      <div v-if="initLoading">
        正在初始化配置数据...
      </div>
      <div v-else>
        <div v-if="!hasInit">
          初始化配置数据失败
        </div>
        <div :style="{padding:`${layout.视图边距}px`}">
          <FormSearch ref="formSearch"></FormSearch>
          <a-table
            size="small"
            bordered
            :customHeaderRow="customHeaderRow"
            :pagination="false"
            :data-source="loadData"
          >
            <a-table-column
              v-for="(column,i) in columns"
              :key="`column${i}`"
              :dataIndex="column.dataIndex"
              :title="column.title">

            </a-table-column>
            <a-table-column fixed="right" :width="80" title="操作">
              <template slot-scope="text,record">
                <a-dropdown>
                  <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                    <i class="fa fa-ellipsis-h"/>
                  </a>
                  <a-menu slot="overlay">
                    <a-menu-item v-show="btn.isShow(record)" v-for="btn in dataBtns" :key="`data-btn-${btn.key}`" >
                      <i :class="`fa ${btn.icon} mr5`"/>{{ btn.name }}
                    </a-menu-item>
                  </a-menu>
                </a-dropdown>
              </template>
            </a-table-column>
          </a-table>
        </div>
      </div>
    </ZgDialog>
  </div>
</template>
<script>
// import dayjs from 'dayjs'
import FormSearch from './FormSearch.vue'
import { STable } from '@/components'

export default {
  components: {
    FormSearch, STable
  },
  props: {
    view: {
      type: Object,
      default: () => {
        return {
          width: '1100px',
          top: '5%',
          height: '500px',
          title: '东曲选煤厂_矿点发运明细表_测试'
        }
      }
    },
    table: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data () {
    return {
      visible: false,
      hasInit: false,
      initLoading: false,
      layout: {},
      columns: [

        {
          title: '规则编号',
          dataIndex: 'no'
        },
        {
          title: '描述',
          dataIndex: 'description'
        },
        {
          title: '服务调用次数',
          dataIndex: 'callNo',
          sorter: true,
          needTotal: true,
          customRender: (text) => text + ' 次'
        },
        {
          title: '状态',
          dataIndex: 'status',
          needTotal: true
        },
        {
          title: '更新时间',
          dataIndex: 'updatedAt',
          sorter: true
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          scopedSlots: { customRender: 'action' }
        }
      ],
       dataBtns: [

        { key: 1, name: '表单配置', icon: 'fa-setting', isShow: () => { return true } },
        { key: 2, name: '环节设计', icon: 'fa-gateway', isShow: () => { return true } }

      ],
      loadData: [
        {
          no: 123,
          description: 'asdf',
          callNo: 12,
          status: 'success',
          updatedAt: '2018-07-26 00:00:00'

        }
      ],
      initFormulas: [],
      changeFormulas: [],
      submitFormulas: [],
      validUrl: '',
      // 是否验证必填项
      isRequiredEnabled: true,
      // 是否验证正则
      isRegexEnabled: true,
      // 是否调用远程验证接口
      isRemoteCheckEnabled: true,
      // 是否执行初始化公式
      isInitFormulaEnabled: true,
      // 是否执行数据变化公式
      isChangeFormulaEnabled: true,
      // 是否执行提交前公式
      isSubmitFormulaEnabled: true,
      obj: null
    }
  },
  mounted () {
    this.init()
  },
  watch: {
    table () {
      this.init()
    },
    obj: {
      handler (newVal, oldVal) {
        if (this.hasInit) {
          // 数据变化时执行公式
          this.isChangeFormulaEnabled && this.doFormula(this.changeFormulas)
        }
      },
      deep: true
    }
  },
  methods: {
    customHeaderRow () {
      return {
        style: {
          background: '#f2f2f2'
        }
      }
    },
    open () {
      this.visible = true
    },
    doFormula (formulas) {
      if (!formulas || formulas.length === 0) { return }
      const arr = []
      formulas.forEach(t => {
        try {
          // eslint-disable-next-line no-eval
          eval(t)
        } catch (e) {
          arr.push(t)
        }
      })
      if (arr.length > 0) {
        this.$error(`有${arr.length}个公式执行错误`)
      }
    },
    init () {
      this.hasInit = false
      this.initLoading = true
      // 获取布局
      // this.layout = JSON.parse(this.table.addLayout)
      // 获取字段
      // this.columns = this.table.addColumns.map(t => {
      //   t.sort = t.sort || 0
      //   t.span = t.span || 24
      //   t.offset = t.offset || 0
      //   return t
      // })
      // this.$nextTick(() => {
      //   this.columns.sort((a, b) => {
      //     return a.sort - b.sort
      //   })
      // })
      // 获取公式
      // const formulas = this.table.formulas.filter(f => {
      //   return f.cata === '新增'
      // })
      // this.initFormulas = formulas.filter(f => {
      //   return f.triggerMode === '初始化时'
      // }).map(f => {
      //   return f.content
      // })
      // this.changeFormulas = formulas.filter(f => {
      //   return f.triggerMode === '数据变化时'
      // }).map(f => {
      //   return f.content
      // })
      // this.submitFormulas = formulas.filter(f => {
      //   return f.triggerMode === '提交时'
      // }).map(f => {
      //   return f.content
      // })
      // // 获取远程校验接口地址
      // this.validUrl = this.table.validUrl
      // // 生产数据对象
      // const json = {}
      // this.columns.forEach(c => {
      //   if (['整数', '浮点数'].includes(c.type)) {
      //     json[c.code] = Number(c.defaultVal) || 0
      //   } else if (['日期'].includes(c.type)) {
      //     json[c.code] = c.defaultVal || dayjs().format('YYYY-MM-DD')
      //   } else if (['日期时间'].includes(c.type)) {
      //     json[c.code] = c.defaultVal || dayjs().format('YYYY-MM-DD HH:mm:ss')
      //   } else if (['单选框', '开关'].includes(c.type)) {
      //     json[c.code] = c.defaultVal === '1'
      //   } else if (['多选'].includes(c.type)) {
      //     json[c.code] = c.defaultVal.split(',') || []
      //   } else {
      //     json[c.code] = c.defaultVal || ''
      //   }
      // })
      // this.obj = json
      // // 初始化时执行公式
      // this.isInitFormulaEnabled && this.doFormula(this.initFormulas)
      // 初始化配置完成
      setTimeout(() => {
        this.initLoading = false
        this.hasInit = true
      }, 1000)
    },
    save () {
      // 验证必填
      if (this.isRequiredEnabled) {
        for (const i in this.columns) {
          const column = this.columns[i]
          const value = this.obj[column.code]
          if (['单选框', '开关', '多选'].includes(column.type)) {
            continue
          }
          if (column.isNeed && (!value || value.length === 0)) {
            this.$error(`${column.name}为必填项`)
            return
          }
        }
      }
      // 验证正则，只验证单行文本
      if (this.isRegexEnabled) {
        const inputColumns = this.columns.filter(c => {
          return c.type === '单行文本' && c.regex && c.regex.length > 0
        })
        for (const i in inputColumns) {
          const column = inputColumns[i]
          const value = this.obj[column.code]
          const reg = new RegExp(column.regex)
          if (!reg.test(value)) {
            this.$error(column.errorMsg)
            return
          }
        }
      }
      // 提交前执行公式
      this.isSubmitFormulaEnabled && this.doFormula(this.submitFormulas)
      // 远程接口验证
      const param = Object.assign({}, this.obj)
      if (this.isRemoteCheckEnabled && this.validUrl && this.validUrl.length > 0) {
        this.$http.post(this.validUrl, param, () => {
          this.$http.post('/zg-autoform/table/data/add/' + this.table.code, param, () => {
            this.visible = false
            this.$emit('ok')
          })
        })
      } else {
        this.$http.post('/zg-autoform/table/data/add/' + this.table.code, param, () => {
          this.visible = false
          this.$emit('ok')
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
